package com.ugrow.ugrowcommunity.activity.moments;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.ugrow.ugrowcommunity.BuildConfig;
import com.ugrow.ugrowcommunity.R;
import com.ugrow.ugrowcommunity.activity.moments.adapter.CommendAdapter;
import com.ugrow.ugrowcommunity.activity.moments.commentBean.Data;
import com.ugrow.ugrowcommunity.databinding.FragmentCommendMsgDialogBinding;
import com.ugrow.ugrowcommunity.util.HttpUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

public class CommendMsgDialogFragment extends BottomSheetDialogFragment {


    private FragmentCommendMsgDialogBinding mBinding;
    private List<Data> commentBeanList;
    private CommendInputDialogFragment mCommendInputDialog;
    private CommendAdapter mCommendAdapter;
    private long authorId;

    public CommendMsgDialogFragment(List<Data> commentBeanList, long authorId) {
        this.commentBeanList = commentBeanList;
        this.authorId = authorId;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置背景透明，才能显示出layout中诸如圆角的布局，否则会有白色底（框）
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.fragment_commend_msg_dialog, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        super.onActivityCreated(savedInstanceState);
        //设置背景为透明
        window.setWindowAnimations(R.style.AnimBottom);
        window.setBackgroundDrawable(ContextCompat.getDrawable(getContext(), android.R.color.transparent));
        //去除阴影
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.dimAmount = 0.1f;
        window.setAttributes(layoutParams);
        getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (mOnDisMissCallBack != null) {
                    mOnDisMissCallBack.onDismiss();
                }
                dismissAllowingStateLoss();
            }
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        RecyclerView mRecyclerView = mBinding.mBottomSheet;
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mCommendAdapter = new CommendAdapter(commentBeanList);
        mRecyclerView.setAdapter(mCommendAdapter);
        mBinding.mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInputDialog("", "1");
            }
        });
        mBinding.mTvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savePost("", "1");
            }
        });

        mCommendAdapter.setOnCommentClickListener(new CommendAdapter.OnCommentClickListener() {
            @Override
            public void onclickListener(String parentId, String level) {
                showInputDialog(parentId, level);
            }
        });
    }

    public void refreshList(List<Data> list) {
        mCommendAdapter.dispatchUpdate(list);
    }

    private void showInputDialog(String parentId, String level) {
        if (mCommendInputDialog == null) {
            mCommendInputDialog = CommendInputDialogFragment.newInstance(mBinding.mTextView.getText().toString());
            mCommendInputDialog.setOnDisMissCallBack(new CommendInputDialogFragment.OnDisMissCallBack() {
                @Override
                public void onDismiss() {
                    mCommendInputDialog = null;
                }

                @Override
                public void saveCommend() {
                    savePost(parentId, level);
                }

                @Override
                public void onCommendTextChanged(String contend) {
                    mBinding.mTextView.setText(contend);
                }
            });
            mCommendInputDialog.show(getChildFragmentManager(), mCommendInputDialog.getTag());
        }
    }


    /**
     * 添加一对一关联，当前用户发布帖子
     */
    private void savePost(String parentId, String level) {
        String content = mBinding.mTextView.getText().toString();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(requireContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("content", mBinding.mTextView.getText().toString());
        map.put("articleId", authorId);
        map.put("parentId", parentId);
        map.put("level", level);
        map.put("authorId", com.ugrow.ugrowcommunity.data.Data.ID);
        HttpUtil.httpPost(BuildConfig.COMMENTS_INSTER, map, HttpUtil.ContentType.JSON, new HttpUtil.CallBack() {
            @Override
            public void success(HttpUtil.Result result) {
                if (result.success && result.code == 200) {
                    Toast.makeText(requireActivity(), "评论成功~", Toast.LENGTH_SHORT).show();
                    if ("1".equals(level)) {
                        mCommendAdapter.addHeaderView(mBinding.mTextView.getText().toString(), String.valueOf(com.ugrow.ugrowcommunity.data.Data.ID));
                    } else if ("2".equals(level)) {
                        mCommendAdapter.addChildHeaderView(mBinding.mTextView.getText().toString(), String.valueOf(com.ugrow.ugrowcommunity.data.Data.ID));
                    }
                    mBinding.mTextView.setText("");

                }
            }

            @Override
            public void failed(IOException e) {
                Toast.makeText(requireActivity(), "评论失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                mBinding.mTextView.setText("");
            }
        });

    }

    public interface OnDisMissCallBack {
        void onDismiss();
    }

    private OnDisMissCallBack mOnDisMissCallBack;

    public void setOnDisMissCallBack(OnDisMissCallBack mOnDisMissCallBack) {
        this.mOnDisMissCallBack = mOnDisMissCallBack;
    }
}